package com.ljh.aiplatform.service.impl;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljh.aiplatform.common.ErrorCode;
import com.ljh.aiplatform.constant.CommonConstant;
import com.ljh.aiplatform.exception.BusinessException;
import com.ljh.aiplatform.exception.ThrowUtils;
import com.ljh.aiplatform.mapper.AppMapper;
import com.ljh.aiplatform.model.dto.app.AppQueryRequest;
import com.ljh.aiplatform.model.entity.App;
import com.ljh.aiplatform.model.entity.User;
import com.ljh.aiplatform.model.enums.AppTypeEnum;
import com.ljh.aiplatform.model.enums.ReviewStatusEnum;
import com.ljh.aiplatform.model.enums.ScoringStrategyEnum;
import com.ljh.aiplatform.model.vo.AppAnalyseVO;
import com.ljh.aiplatform.model.vo.AppVO;
import com.ljh.aiplatform.model.vo.UserVO;
import com.ljh.aiplatform.service.AppService;
import com.ljh.aiplatform.service.UserService;
import com.ljh.aiplatform.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * 应用服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements AppService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param app
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validApp(App app, boolean add) {
//        add参数的值为true时表示添加新数据，为false时表示修改现有数据。
        ThrowUtils.throwIf(app == null, ErrorCode.PARAMS_ERROR);
        //创建时，必填项不能为空
        if(add){
            String appName = app.getAppName();
            String appDesc = app.getAppDesc();
            ThrowUtils.throwIf(StringUtils.isAnyBlank(appName,appDesc), ErrorCode.PARAMS_ERROR, "必填项不能为空");
            Integer appType = app.getAppType();
            ThrowUtils.throwIf(Optional.ofNullable(appType).isEmpty(), ErrorCode.PARAMS_ERROR, "应用类型不能为空");
            final AppTypeEnum enumByValue = AppTypeEnum.getEnumByValue(appType);
            ThrowUtils.throwIf(enumByValue == null, ErrorCode.PARAMS_ERROR, "应用类型错误");
            Integer scoringStrategy = app.getScoringStrategy();
            ThrowUtils.throwIf(Optional.ofNullable(scoringStrategy).isEmpty(), ErrorCode.PARAMS_ERROR, "评分策略不能为空");
            final ScoringStrategyEnum enumByValue1 = ScoringStrategyEnum.getEnumByValue(scoringStrategy);
            ThrowUtils.throwIf(enumByValue1 == null, ErrorCode.PARAMS_ERROR, "评分策略错误");
        }
        //如果是修改
        // 补充校验规则
        if (StringUtils.isNotBlank(app.getAppName())) {
            ThrowUtils.throwIf(app.getAppName().length() > 80, ErrorCode.PARAMS_ERROR, "应用名称要小于 80");
        }
        if (app.getReviewStatus() != null) {
            ReviewStatusEnum reviewStatusEnum = ReviewStatusEnum.getEnumByValue(app.getReviewStatus());
            ThrowUtils.throwIf(reviewStatusEnum == null, ErrorCode.PARAMS_ERROR, "审核状态非法");
        }
    }

    /**
     * 获取查询条件
     *
     * @param appQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<App> getQueryWrapper(AppQueryRequest appQueryRequest) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        if (appQueryRequest == null) {
            return queryWrapper;
        }
        String appName = appQueryRequest.getAppName();
        String appDesc = appQueryRequest.getAppDesc();
        String appIcon = appQueryRequest.getAppIcon();
        Integer appType = appQueryRequest.getAppType();
        Integer scoringStrategy = appQueryRequest.getScoringStrategy();
        Integer reviewStatus = appQueryRequest.getReviewStatus();
        Long reviewerId = appQueryRequest.getReviewerId();
        Long userId = appQueryRequest.getUserId();
        String searchText = appQueryRequest.getSearchText();
        int current = appQueryRequest.getCurrent();
        int pageSize = appQueryRequest.getPageSize();
        String sortField = appQueryRequest.getSortField();
        String sortOrder = appQueryRequest.getSortOrder();
        App app = new App();
        BeanUtils.copyProperties(appQueryRequest, app);
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("appDesc", searchText).or().like("appName", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(appName),"appName", appName);
        queryWrapper.like(StringUtils.isNotBlank(appDesc),"appDesc", appDesc);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(appIcon), "appIcon", appIcon);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appType), "appType", appType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(scoringStrategy), "scoringStrategy", scoringStrategy);
        queryWrapper.eq(ObjectUtils.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjectUtils.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        /**
         * 首先通过SqlUtils.validSortField(sortField)验证sortField是否是一个有效的排序字段。
         * 然后根据sortOrder是否等于CommonConstant.SORT_ORDER_ASC来决定排序顺序是升序还是降序。
         * 最后，将验证后的排序字段和排序顺序应用到queryWrapper对象上，以便在执行查询时使用
         */
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取应用封装
     *
     * @param app
     * @param request
     * @return
     */
    @Override
    public AppVO getAppVO(App app, HttpServletRequest request) {
        // 对象转封装类
        AppVO appVO = AppVO.objToVo(app);
        // 1. 关联查询用户信息
        Long userId = app.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        appVO.setUser(userVO);
        return appVO;
    }

    /**
     * 分页获取应用封装
     *
     * @param appPage
     * @param request
     * @return
     */
    @Override
    public Page<AppVO> getAppVOPage(Page<App> appPage, HttpServletRequest request) {
        List<App> appList = appPage.getRecords();
        Page<AppVO> appVOPage = new Page<>(appPage.getCurrent(), appPage.getSize(), appPage.getTotal());
        if (CollUtil.isEmpty(appList)) {
            return appVOPage;
        }
        // 对象列表 => 封装对象列表
        List<AppVO> appVOList = appList.stream().map(app -> AppVO.objToVo(app))
                .collect(Collectors.toList());
        appVOPage.setRecords(appVOList);
        //关联查询用户信息
        Set<Long> userIdSet = appList.stream().map(App::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<AppVO> postVOList = appList.stream().map(app -> {
            AppVO appVO = AppVO.objToVo(app);
            Long userId = app.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            appVO.setUser(userService.getUserVO(user));
            return appVO;
        }).collect(Collectors.toList());
        appVOPage.setRecords(postVOList);
        return appVOPage;
    }

}
